from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from oauth.models import OAuthQQUser
from oauth.serializers import OauthQQUserSerializer
from oauth.utils import generic_access_tocken

"""
获取code
通过code获取token
通过token获取openid
"""
from QQLoginTool.QQtool import OAuthQQ
# from mall import settings
from django.conf import settings


# 给前端返回url
class OauthQQURLView(APIView):
    def get(self, request):
        state = '/'
        # 创建对象 client_id=None, client_secret=None, redirect_uri=None, state=None
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=state
                        )
        # 获取方法,生成url
        login_url = oauth.get_qq_url()
        # 返回响应
        return Response({"login_url": login_url})


# 通过code获取token,openid
class OauthQQUserView(APIView):
    def get(self, request):
        # 获取code
        code = request.query_params.get('code')
        if code is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 换取token
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        )
        access_token = oauth.get_access_token(code)
        # 获取openid
        openid = oauth.get_open_id(access_token)

        # 如果数据库中有openid说明已绑定用户,如果没有则未绑定
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 说明没有绑定过
            # 对敏感数据进行处理
            openid = generic_access_tocken(openid)
            return Response({'access_token': openid})
        else:
            # 说明绑定过,返回token,进行登陆
            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(qquser.user)
            token = jwt_encode_handler(payload)

            return Response({
                'token': token,
                'user_id': qquser.user.id,
                'username': qquser.user.username
            })

    """
       用户点击绑定按钮的时候,前端应该将 手机号,密码,openid,sms_code 发送给后端

       1. 接收数据
       2. 对数据进行校验
           2.1 校验 openid 和sms_code
           2.2 判断手机号
               如果注册过,需要判断 密码是否正确
               如果没有注册过,创建用户
       3. 保存数据
           3.1保存 user 和 openid
       4. 返回响应

       POST

    """

    def post(self, request):

        # 1. 接收数据
        data = request.data
        # 2. 对数据进行校验
        #     2.1 校验 openid 和 sms_code
        #     2.2 判断手机号
        #         如果注册过,需要判断 密码是否正确
        #         如果没有注册过,创建用户
        serializer = OauthQQUserSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        # 3. 保存数据
        qquser = serializer.save()
        #     3.1保存 user 和 openid
        # 4. 返回响应  返回token,进行登陆

        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(qquser.user)
        token = jwt_encode_handler(payload)

        return Response({
            'user_id': qquser.user.id,
            'username': qquser.user.username,
            'token': token
        })

#
# # 加密签名
# # from itsdangerous import JSONWebSignatureSerializer # 错误的
# from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadSignature,SignatureExpired
# from django.conf import settings
# # 1.创建 序列化器
# #secret_key             秘钥,一般使用工程的 SECRET_KEY
# # expires_in=None       有效期 单位秒
# serializer = Serializer(settings.SECRET_KEY,3600)
#
# #2. 组织 加密数据
# data = {'openid':'1234567890'}
#
# #3.进行加密处理
# token = serializer.dumps(data)
#
# """
# eyJleHAiOjE1NDE2NTA2MjIsImFsZyI6IkhTMjU2IiwiaWF0IjoxNTQxNjQ3MDIyfQ.
# eyJvcGVuaWQiOiIxMjM0NTY3ODkwIn0.
# 4jI3L-_nDa52WPmI_pnLUbqLs0DxIhkb3ZEqpWLCVUo
#
# """
#
# #4.对数据进行解密
# serializer.loads(token)
#
#
#
# #5.有效期
# serializer = Serializer(settings.SECRET_KEY,1)
#
#
# data = {'openid':'1234567890'}
#
# token = serializer.dumps(data)
#
#
# serializer.loads(token)
